/* Copyright (c) 2024 Huawei Technologies Co., Ltd.
openFuyao is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
         http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN 'AS IS' BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details. */

import BreadCrumbCom from '@/components/BreadCrumbCom';
import { Button, Popover, Space, Tabs, message } from 'antd';
import { useEffect, useRef, useState, useCallback } from 'openinula';
import { DownOutlined } from '@ant-design/icons';
import PriorityDetail from '@/pages/SchedulingPolicyConfiguration/PriorityDetail';
import PriorityYaml from '@/pages/SchedulingPolicyConfiguration/PriorityYaml';
import { useHistory, useLocation } from 'inula-router';
import { getSpecifiedPriorityClasses } from '@/api/schedulingApi';
import { solveAnnotation, solveAnnotationOrLabelDiff } from '@/tools/utils';
import AnnotationModal from '@/components/AnnotationModal';
import DeleteInfoModal from '@/components/DeleteInfoModal';
import { deleteSpecifiedPriorityClasses, editAnnotationsOrLabels } from '@/api/schedulingApi';
import { ResponseCode } from '@/common/constants';
import '@/styles/priorityClassDetails.less';
import { jsonToYaml } from '@/tools/utils';

export default function PriorityClassUpdate() {
  const history = useHistory();
  const [messageApi, contextHolder] = message.useMessage();
  const [popOpen, setPopOpen] = useState(false);
  const location = useLocation();
  const queryParams = new URLSearchParams(location.search);
  const [detailsInfo, setDetailsInfo] = useState({});
  const priorityName = queryParams.get('priorityName');
  const [isEdit, setIsEdit] = useState(queryParams.get('isEdit') === 'true');
  const [isAnnotationModalOpen, setIsAnnotationModalOpen] = useState(false);
  const [isLabelModalOpen, setIsLabelModalOpen] = useState(false);
  const [oldAnnotations, setOldAnnotataions] = useState('');
  const [oldLabels, setOldLabels] = useState('');
  const buttonRef = useRef(null);
  const [priorityModalOpen, setPriorityModalOpen] = useState(false); // 删除对话框展示
  const [isPriorityDelCheck, setIsPriorityDelCheck] = useState(false); // 是否选中
  const [isReadyOnly, setIsReadyOnly] = useState(false); // 是否只读
  const [activeKey, setActiveKey] = useState('2');
  const [yamlData, setYamlData] = useState('');
  const [priorityLoading, setPriorityLoading] = useState(false);

  const handlePopOpenChange = () => {
    setPopOpen((open) => !open);
  };

  const getSpecifiedPriorityClassesInfo = async (name) => {
    setPriorityLoading(false);
    try {
      const res = await getSpecifiedPriorityClasses(name);
      if (res.status === 200) {
        setYamlData(jsonToYaml(JSON.stringify(res.data)));
        res.data.metadata.labels = solveAnnotation(res.data.metadata.labels);
        res.data.metadata.annotations = solveAnnotation(res.data.metadata.annotations);
        setDetailsInfo(res.data);
        setPriorityLoading(true);
      }
    } catch (e) {
      message.error('加载失败');
    }
  };

  // 注解失败回调
  const handleAnnotationCancel = () => {
    setIsAnnotationModalOpen(false);
  };

  // 注解成功回调
  const handleAnnotationOk = async (data) => {
    if (JSON.stringify(oldAnnotations) === JSON.stringify(data)) {
      messageApi.info('注解未进行修改');
      setIsAnnotationModalOpen(false);
    } else {
      const keyArrPriorityClassUpdateAnnnttation = [];
      data.map(item => keyArrPriorityClassUpdateAnnnttation.push(item.key));
      if (keyArrPriorityClassUpdateAnnnttation.filter((item, index) => keyArrPriorityClassUpdateAnnnttation.indexOf(item) !== index).length) {
        messageApi.error('存在相同key!');
      } else {
        // 请求接口添加
        // 比较前后是否一致 返回处理后的注解
        const addAnnotationListPriorityClassUpdate = solveAnnotationOrLabelDiff(oldAnnotations, data, 'annotation');
        try {
          const res = await editAnnotationsOrLabels(priorityName, addAnnotationListPriorityClassUpdate);
          if (res.status === ResponseCode.OK) {
            message.success('编辑注解成功');
            setTimeout(() => {
              getSpecifiedPriorityClassesInfo(priorityName);
              setIsAnnotationModalOpen(false);
            }, 1000);
          }
        } catch (error) {
          if (error.response.status === 403) {
            message.error('操作失败，当前用户没有操作权限，请联系管理员添加权限!');
          } else {
            message.error(`编辑注解失败！${error.response.data.message}`);
          }
        }
      }
    }
  };

  // 标签成功回调
  const handleLabelOk = async (data) => {
    if (JSON.stringify(oldLabels) === JSON.stringify(data)) {
      messageApi.info('标签未进行修改');
      setIsLabelModalOpen(false);
    } else {
      const keyArrPriorityClassUpdateLabel = [];
      data.map(item => keyArrPriorityClassUpdateLabel.push(item.key));
      if (keyArrPriorityClassUpdateLabel.filter((item, index) => keyArrPriorityClassUpdateLabel.indexOf(item) !== index).length) {
        messageApi.error('存在相同key!');
      } else {
        // 请求接口添加
        // 比较前后是否一致 返回处理后的注解
        const addLabelListPriorityClassUpdateLabel = solveAnnotationOrLabelDiff(oldLabels, data, 'label');
        try {
          const res = await editAnnotationsOrLabels(priorityName, addLabelListPriorityClassUpdateLabel);
          if (res.status === ResponseCode.OK) {
            message.success('编辑标签成功');
            setTimeout(() => {
              getSpecifiedPriorityClassesInfo(priorityName);
              setIsLabelModalOpen(false);
            }, 1000);
          }
        } catch (error) {
          if (error.response.status === 403) {
            message.error('操作失败，当前用户没有操作权限，请联系管理员添加权限!');
          } else {
            message.error(`编辑标签失败！${error.response.data.message}`);
          }
        }
      }
    }
  };

  const handleEdit = () => {
    setPopOpen(false);
    setActiveKey('2');
    setIsReadyOnly(false);
  };

  // 标签失败回调
  const handleLabelCancel = () => {
    setIsLabelModalOpen(false);
  };

  // 取消删除
  const handleDelCancelPriorityIndex = () => {
    setPriorityModalOpen(false);
  };

  const handlePriorityCheckFn = (e) => {
    setIsPriorityDelCheck(e.target.checked);
  };

  const handleDelPriorityConfirm = async () => {
    try {
      const res = await deleteSpecifiedPriorityClasses(priorityName);
      if (res.status === ResponseCode.OK) {
        message.success('删除成功！');
        setPriorityModalOpen(false);
        setIsPriorityDelCheck(false);
        setTimeout(() => {
          history.push('/SchedulingPolicyConfiguration/PriorityClass');
        }, 1000);
      }
    } catch (error) {
      if (error.response.status === 403) {
        message.error('操作失败，当前用户没有操作权限，请联系管理员添加权限!');
      } else {
        message.error(error.response?.data.message);
      }
    }
  };

  // 删除按钮
  const handleDeletePriorityIndex = (name) => {
    // 隐藏气泡框
    setPopOpen(false);
    setPriorityModalOpen(true); // 打开弹窗
    setIsPriorityDelCheck(false);
  };

  const handleReadyOnly = (bool) => {
    setIsReadyOnly(bool);
  };

  const items = [
    {
      key: '1',
      label: '详情',
      children: <PriorityDetail details={detailsInfo} refreshFn={() => getSpecifiedPriorityClassesInfo(priorityName)} />,
    },
    {
      key: '2',
      label: 'YAML',
      children: <PriorityYaml priorityName={priorityName} details={yamlData} readOnly={isReadyOnly} handleEditFn={handleReadyOnly} />,
    },
  ];

  const onChange = (e) => {
    setActiveKey(e);
  };

  useEffect(() => {
    getSpecifiedPriorityClassesInfo(priorityName);
  }, [priorityName]);
  return (
    <div className='priorityClassDetails_container' id='priority'>
      <div>
        <BreadCrumbCom items={[
          { title: '调度策略配置', disabled: true },
          { title: 'PriorityClass', path: '/SchedulingPolicyConfiguration/PriorityClass' },
          { title: '详情', path: '/SchedulingPolicyConfiguration/priorityClassDetails' },
        ]} />
      </div>
      <div className='priority_header'>
        <div className='priority_title'>{priorityName}</div>
        <div ref={buttonRef}>
          <Popover
            placement='bottom'
            getPopupContainer={() => document.getElementById('priority')}
            content={
              <Space className='column_pop' getContainer={false}>
                <Button type='link' onClick={handleEdit}>修改</Button>
                <Button type='link' onClick={() => {
                  setIsLabelModalOpen(true);
                  setPopOpen(false);
                }}>
                  修改标签
                </Button>
                <Button type='link' onClick={() => {
                  setIsAnnotationModalOpen(true);
                  setPopOpen(false);
                }}>
                  修改注解
                </Button>
                <Button type='link' onClick={() => handleDeletePriorityIndex(priorityName)}>
                  删除
                </Button>
              </Space>
            }
            trigger="click"
            open={popOpen}
            onOpenChange={handlePopOpenChange}
          >
            <Button className='primary_btn'>
              操作 <DownOutlined className='small_margin_adjust' />
            </Button>
          </Popover>
        </div>
      </div>
      {priorityLoading && <Tabs items={items} style={{ backgroundColor: '#fff' }} activeKey={activeKey} onChange={onChange} />}
      {priorityLoading && <AnnotationModal open={isLabelModalOpen} type="label" dataList={detailsInfo.metadata?.labels} callbackOk={handleLabelOk} callbackCancel={handleLabelCancel} />}
      {priorityLoading && <AnnotationModal open={isAnnotationModalOpen} type="annotation" dataList={detailsInfo.metadata?.annotations} callbackOk={handleAnnotationOk} callbackCancel={handleAnnotationCancel} />}
      <DeleteInfoModal
        title='删除PriorityClass'
        open={priorityModalOpen}
        cancelFn={handleDelCancelPriorityIndex}
        content={[
          '删除后将无法恢复，请谨慎操作。',
          `确定删除 ${priorityName} 吗？`,
        ]}
        isCheck={isPriorityDelCheck}
        confirmFn={handleDelPriorityConfirm}
        showCheck={true}
        checkFn={handlePriorityCheckFn}
      />
    </div>
  );
};